// index.js
// 获取应用实例
import translate from "../../utils/translate.js"
import formatTime  from "../../utils/date.js"

const app = getApp()
Page({
  data: {
    content:"",
    q:"",
    chs:""
  },
  onShow(){
    this.setData({chs:wx.getStorageSync('currentLan')})
    if(this.data.q && wx.getStorageSync('changeLan')){
      const to = app.globalData.lanList.find(item => item.chs === this.data.chs).lang
      translate(this.data.q,to).then(
        value =>{
          wx.hideLoading()
          
          this.setData({content:value.trans_result.map(item=>item.dst).join('')})
          wx.setStorageSync('fromLang', value.from)
          const a = wx.getStorageSync('history')
          const fromLang = app.globalData.lanList.find(item =>item.lang ==  value.from).chs
          a.unshift({fromLang:fromLang,toLang:this.data.chs,content:this.data.q,text:value.trans_result.map(item=>item.dst).join(''),date:formatTime(new Date())})
          wx.setStorageSync('history', a)
          console.log(wx.getStorageSync('history'))
        },
        result =>{ 
          wx.hideLoading()
          wx.showToast({
            title: '翻译失败',
          })
          setTimeout(()=>{ wx.hideToast()},1000)  
        }
      )
    }
  },
  onHide(){wx.setStorageSync('changeLan', false)},
  goToChange(){
    wx.navigateTo({
      url:"/pages/change/change"
    })
  },
  clear(){
    this.setData({q:"",content:''})
  },
  inp(e){
    this.setData({
      q:e.detail.value
    })
  },
  tran(){
    if (!this.data.q) return
    if(this.data.content&&wx.getStorageSync('history')[0]?.content == this.data.q) return
    const to = app.globalData.lanList.find(item => item.chs === this.data.chs).lang
      translate(this.data.q,to).then(
        value =>{
          wx.hideLoading()
          this.setData({content:value.trans_result.map(item=>item.dst).join('')})
          wx.setStorageSync('fromLang', value.from)
          const a = wx.getStorageSync('history')
          const fromLang = app.globalData.lanList.find(item =>item.lang ==  value.from).chs
          a.unshift({fromLang:fromLang,toLang:this.data.chs,content:this.data.q,text:value.trans_result.map(item=>item.dst).join(''),date:formatTime(new Date())})
          console.log("a",a)
          wx.setStorageSync('history', a)
          console.log(wx.getStorageSync('history'))
        },
        result =>{ 
          wx.hideLoading()
          wx.showToast({
            title: '翻译失败',
          })
          setTimeout(()=>{ wx.hideToast()},1000)  
        }
      )
  }
})
